﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business.DwzFrame;
using NHibernate;
using ZLCMS.Business;
using NHibernate.Transform;
using ZLCMS.Business.Util;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class CustomizeMenuStatistics : System.Web.UI.Page
    {
        protected FrameHelper _framePage;

        public string _s_title, _s_sdate, _s_edate;

        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            //初始化全局变量值
            _s_title = Request["s_title"] == null ? "" : Request["s_title"];
            _s_sdate = Request["s_sdate"] == null ? "" : Request["s_sdate"];
            _s_edate = Request["s_edate"] == null ? "" : Request["s_edate"];

            ////初始化控件值

            tb_search_title.Text = _s_title;
            tb_search_bdate.Text = string.IsNullOrEmpty(_s_sdate)? DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd") : _s_sdate;
            tb_search_edate.Text = string.IsNullOrEmpty(_s_edate) ? DateTime.Now.ToString("yyyy-MM-dd") : _s_edate;

            //初始化DWZ分页控件
            _framePage = new FrameHelper(this);

            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                string sql = " SELECT STAT_DATE, KEYWORD, COUNT(1) as STAT_SUM from Wx_Statistics_Keyword where Owner_Account = '" + _userAccount + "' and Kind = 'KEYWORD' and opt_date > :sdate and opt_date < :edate ";

                if (!string.IsNullOrEmpty(_s_title))
                {
                    sql += " and Keyword = :keyword ";
                }
                sql += " GROUP BY STAT_DATE, KEYWORD ";

                IQuery countQuery = session.CreateSQLQuery("select count(*) from (" + sql + ") as tmp_Statistics_Keyword ");

                SetupCondition(ref countQuery);

                _framePage.RecordCount = Convert.ToInt32(countQuery.UniqueResult());


                IQuery listQuery = session.CreateSQLQuery(sql);
                SetupCondition(ref listQuery);
                listQuery.SetFirstResult((_framePage.PageIndex - 1) * _framePage.PageSize).SetMaxResults(_framePage.PageSize);

                grid.DataSource = listQuery.SetResultTransformer(Transformers.AliasToEntityMap).List();
                grid.DataBind();
            }
        }

        /// <summary>
        /// 填充查询条件
        /// </summary>
        /// <param name="criteria"></param>
        private void SetupCondition(ref IQuery query)
        {
            query.SetParameter("sdate", DateTime.Parse(_s_sdate + " 00:00:00"));
            query.SetParameter("edate", DateTime.Parse(_s_edate + " 23:59:59"));

            if (!string.IsNullOrEmpty(_s_title))
            {
                query.SetParameter("keyword", _s_title);
            }
        }
        
    }
}
